package com.wy.Listener;

import com.wy.bean.User;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.ArrayList;

@WebListener
public class LoginListener implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        ServletContext servletContext = event.getSession().getServletContext();
        Object attribute = servletContext.getAttribute("userList");
        if (attribute == null) {
            ArrayList<User> users = new ArrayList<>();
            servletContext.setAttribute("userList",users);
        }
        ArrayList<User> userList = (ArrayList<User>)attribute;
        User value = (User) event.getValue();
        userList.add(value);

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        ServletContext servletContext = event.getSession().getServletContext();
        ArrayList<User> userList = (ArrayList<User>) servletContext.getAttribute("userList");
        User user = (User) event.getValue();
        userList.remove(user);
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        ServletContext servletContext = event.getSession().getServletContext();
        ArrayList<User> userList = (ArrayList<User>) servletContext.getAttribute("userList");
        User user = (User) event.getValue();
        userList.add(user);
    }
}
